/*
 * Galaxium Messenger
 * Copyright (C) 2008 Jensen Somers <jensen.somers@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Diagnostics;

using Anculus.Core;
using Galaxium.Core;

namespace Galaxium.Client
{
	/// <summary>
	/// Song information backend used to obtain information from the amarok
	/// media player.
	/// </summary>
	public sealed class AmarokSongInformationBackend : AbstractSongInformationBackend
	{
		private string GetInfo(string what)
		{
			try
			{
				ProcessStartInfo processStartInfo = new ProcessStartInfo("dcop", "amarok default " + what);
				processStartInfo.CreateNoWindow = true;
				processStartInfo.RedirectStandardOutput = true;
				processStartInfo.UseShellExecute = false;
				
				Process process = new Process();
				process.StartInfo = processStartInfo;
				process.Start();
				
				return process.StandardOutput.ReadToEnd();
			}
			catch (Exception ex)
			{
				//TODO: Might need to fix this in a more proper way
				Log.Debug("Amarok GetInfo Exception: " + ex.Message);
				return String.Empty;
			}
		}
		
		public override string Name
		{
			get { return "Amarok"; }
		}
		
		public override bool IsAvailable()
		{
			try
			{
				string info = this.GetInfo("status");
				// The result should be either one of the following:
				// 0 - Off
				// 1 - Paused
				// 2 - Playing
				switch (Convert.ToInt32(info))
				{
				case 1:
				case 2:
					return true;
				default:
					return false;
				}
			}
			catch
			{
				return false;
			}
		}
		          
		public override void Initialize()
		{
		}
		
		public override void Unload()
		{
		}
		
		public override SongInformation GetCurrentSong ()
		{
			if (IsAvailable())
			{
				SongInformation si = new SongInformation (
					this.GetInfo("artist"),
				        this.GetInfo("title"),
				        this.GetInfo("album"),
				        Convert.ToInt32(this.GetInfo("trackTotalTime"))
				);
				
				
				
				return si;                               
			}
			
			return null;
		}		
	}
}